package cn.edu.sdjzu.xg.eagle.controller;

import cn.edu.sdjzu.xg.eagle.dao.TeacherService;
import cn.edu.sdjzu.xg.eagle.entity.Teacher;
import cn.edu.sdjzu.xg.eagle.util.Condition;
import cn.edu.sdjzu.xg.eagle.util.ControllerHelper;
import cn.edu.sdjzu.xg.eagle.util.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;

@WebServlet("/teacherRead.ctl")
public class TeacherReadCtrl extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        JSONObject messageJson = new JSONObject();

        try {
            String reqJsonStr = JSONUtil.getJSON(request);
            JSONObject reqJsonObj = JSON.parseObject(reqJsonStr);

            List<Condition> conditionList = ControllerHelper.getConditions(reqJsonObj);

            Collection<Teacher> teacherList = TeacherService.getInstance().findAll(conditionList);

            // 使用 fastjson2 进行序列化（无需额外选项）
            String teachersJson = JSON.toJSONString(teacherList);
            messageJson.put("data", JSON.parse(teachersJson)); // 放入真正的 JSON 对象，而非字符串
            response.getWriter().println(messageJson);

        } catch (Exception e) {
            messageJson.put("message", "查询失败: " + e.getMessage());
            response.getWriter().println(messageJson);
            e.printStackTrace();
        }
    }
}